/**
 * NetUitl 网络请求的实现
 * @author chenliang
 * @date 2017-01-22
 * https://github.com/facebook/react-native
 */
'use strict';
import React, {Component} from 'react';
import sign from './sign'

import {
    NativeModules
} from 'react-native';

import {toast, hideLoading, getConfig, configkey} from '../utils/NativeUtil';

var LoginOutPlugin = NativeModules.LoginOutPlugin;

class NetUitl extends React.Component {

    static serializeJSON(data) {
        return Object.keys(data).map(function (keyName) {
            return encodeURIComponent(keyName) + '=' + encodeURIComponent(data[keyName])
        }).join('&');
    }

    static postSign(url, data, callback) {
        getConfig(configkey.UserToken, (values) => {
            var token = values[configkey.UserToken];
            console.log(token);
        let headers = {};
        if (token != "") {
            headers = {
                "Content-Type": "application/x-www-form-urlencoded",
                "Accept": "application/json",
                "Authorization": "Bearer " + token,
            }
        } else {
            headers = {
                "Content-Type": "application/x-www-form-urlencoded",
                "Accept": "application/json"
            }
        }
        var fetchOptions = {
            method: 'POST',
            headers: headers,
            body: NetUitl.serializeJSON(sign.api(data))
        };

        fetch(url, fetchOptions)
            .then((response) => {
                if (response.status == 599) {
                    toast("您的请求过于频繁，请稍后再试");
                } else {
                    return response.text()
                }
            })
            .then((responseText) => {
                let responseJson = JSON.parse(responseText);
                if (!responseJson.success) {
                    if (responseJson.message) {
                        toast(responseJson.message);
                    }
                } else {
                    callback(responseJson);
                }
            }).catch(function (e) {
            hideLoading();
        }).done();
        });
    }

    //post请求
    /**
     *url :请求地址
     *data:参数
     *callback:回调函数
     */
    static postFrom(url, data, callback) {
        var fetchOptions = {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: 'data=' + data + ''//这里我参数只有一个data,大家可以还有更多的参数
        };

        fetch(url, fetchOptions)
            .then((response) => response.text())
            .then((responseText) => {
                callback(JSON.parse(responseText));
            }).done();
    }

    /**
     *url :请求地址
     *data:参数(Json对象)
     *callback:回调函数
     */
    static postJson(url, data, callback) {
        var fetchOptions = {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                //json形式
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        };

        fetch(url, fetchOptions)
            .then((response) => response.text())
            .then((responseText) => {
                callback(JSON.parse(responseText));
            }).done();
    }

    //get请求
    /**
     *url :请求地址
     *callback:回调函数
     */
    static  get(url, callback) {
        fetch(url)

            .then((response) => response.text())
            .then((responseText) => {
                callback(JSON.parse(responseText));
            }).done();
    }

    static getAliyun(url, appcode, data, callback) {
        let fetchOptions = {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/x-www-form-urlencoded',
                'Authorization': 'APPCODE ' + appcode
            }
        };
        console.log(fetchOptions);
        fetch(url + "?" + NetUitl.serializeJSON(data), fetchOptions)
            .then((response) => {
                if (response.status == 200) {
                    return response.text()
                }
            })
            .then((responseText) => {
                callback(JSON.parse(responseText));
            }).done();
    }

}

export default NetUitl;
